package com.example.javafx;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class SerialPortSelector extends Application {
    public ImageView imageView;
    public TextField textArea_id;
    public String updateTime="";
    public Label label;
    public Date date1_up;
    public String fileUrl="C:\\Users\\23659\\Desktop\\yolov5-master\\yolov5-master\\yuan.jpg";
    public SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public String fileName="xxx";
    public Label label2;
    public Label label_status1;
    public GridPane root;
    public FlowPane flowPane;
    @Override
    public void start(Stage primaryStage) {
        Date date=new Date();
        updateTime = format.format(date);
        // 加载图像（这里只是一个示例，你需要替换为实际的图像源）
        Image image = new Image(fileUrl);
        File file=new File(fileUrl);
        fileName=file.getName();
        long l = file.lastModified();
        date1_up=new Date(l);

        // 创建ImageView
        imageView = new ImageView(image);
        imageView.setFitHeight(image.getHeight()/1.2);
        imageView.setFitWidth(image.getWidth());
        // 确保图像在ImageView中完全显示并保持纵横比


        // 添加点击事件监听器
        imageView.setOnMouseClicked(event -> {
            label.setTextFill(Color.RED);
            // 获取点击的坐标（这是相对于ImageView的坐标）
            double x = event.getX()*3;
            double y = event.getY()*1.2*3;

            // 转换为图像上的坐标（如果ImageView进行了缩放，这里需要进行相应的转换）
            // 但在这个例子中，因为设置了fitWidth和fitHeight，并且preserveRatio为true，
            // 所以x和y已经是相对于原始图像尺寸的缩放坐标
            this.click(x,y);


        });

        // 将ImageView放入StackPane中
        root = new GridPane();
        //StackPane root = new StackPane(imageView);

        root.add(imageView, 0, 0);
        textArea_id=new TextField("1-10");
        textArea_id.setMaxWidth(50);
        flowPane=new FlowPane();
        Label label_HID_ID=new Label("HID设备:");
        flowPane.getChildren().add(label_HID_ID);
        flowPane.getChildren().add(textArea_id);
        //垂直间距
        flowPane.setVgap(10);
        flowPane.setOrientation(Orientation.VERTICAL);
        root.add(flowPane,1,0);
        Button button_slip_r=new Button("右滑");
        button_slip_r.setOnAction(e->{
            label.setTextFill(Color.RED);

            this.inte_slip(900,1459,195,1557);
        });
        Button button_slip_l=new Button("左滑");
        button_slip_l.setOnAction(e->{
            label.setTextFill(Color.RED);

            this.inte_slip(195,1557,900,1459);
        });
        Button button_slip_u=new Button("上滑");
        button_slip_u.setOnAction(e->{
            label.setTextFill(Color.RED);
            this.inte_slip(568,1638,562,664);
        });
        Button button_slip_b=new Button("下滑");
        button_slip_b.setOnAction(e->{
            label.setTextFill(Color.RED);

            this.inte_slip(562,664,664,1638);
        });
        Button button_exit=new Button("退出");
        button_exit.setOnAction(e->{
            System.exit(0);

            //this.get("http://localhost:8080/api/getAllDevices",null);

        });
        Button button_jiesuo=new Button("解锁");
        button_jiesuo.setOnAction(e->{
            label.setTextFill(Color.RED);
            this.inte_slip(568,1638,562,664);
            try {
                Thread.sleep(1000);
                this.click(563,1471);//2
                Thread.sleep(500);
                this.click(870,1455);//3
                Thread.sleep(500);
                this.click(895,1700);//6
                Thread.sleep(500);
                this.click(548,1667);//5
                Thread.sleep(500);
                this.click(845,1891);//9
                Thread.sleep(500);
                this.click(254,1446);//1
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        });
        Button button_zhucheng=new Button("运行主程序");
        button_zhucheng.setOnAction(e->{

            Map<String,Object> map=new HashMap<>();
            map.put("zhu","1");
            this.setZhu("http://127.0.0.1:5000/setzhu",map);
        });
        Button button_douping=new Button("投屏");
        button_douping.setOnAction(e->{
            label.setTextFill(Color.RED);

            Map<String,Object> map=new HashMap<>();
            map.put("zhu","4");
            this.setZhu("http://127.0.0.1:5000/setzhu",map);
        });
        Button button = new Button("设置设备文件");
        button.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();

            // 设置文件选择器的标题
            fileChooser.setTitle("选择图片");

            // 设置文件选择器的默认目录（可选）
             fileChooser.setInitialDirectory(new File("C:\\Users\\23659\\Desktop\\yolov5-master\\yolov5-master"));

            // 添加文件扩展名过滤器（可选）
            FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Text Files", "*.jpg;*.png;*.jpeg");
            fileChooser.getExtensionFilters().add(filter);

            // 显示文件选择器并打开文件
            File selectedFile = fileChooser.showOpenDialog(primaryStage);

            if (selectedFile != null) {
                // 在这里处理选择的文件，例如显示文件名
                System.out.println("File selected: " + selectedFile.getAbsolutePath());
                fileUrl=selectedFile.getAbsolutePath();
                fileName=selectedFile.getName();
                label2.setText(fileName);
            }
        });
        Label label_Up=new Label("刷新时间");
        label=new Label(updateTime);
        Label label1=new Label("当前设备文件");
        label2=new Label(fileName);
        Label label_status=new Label("当前设备运行状态：");
        label_status1=new Label("停止");
        label_status1.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
        flowPane.getChildren().add(button_slip_r);
        flowPane.getChildren().add(button_slip_l);
        flowPane.getChildren().add(button_slip_u);
        flowPane.getChildren().add(button_slip_b);
        flowPane.getChildren().add(button_exit);
        flowPane.getChildren().add(button_jiesuo);
        flowPane.getChildren().add(button_zhucheng);
        flowPane.getChildren().add(button_douping);
        flowPane.getChildren().add(label_Up);
        flowPane.getChildren().add(label);
        flowPane.getChildren().add(button);
        flowPane.getChildren().add(label1);
        flowPane.getChildren().add(label2);
        flowPane.getChildren().add(label_status);
        flowPane.getChildren().add(label_status1);

        // 设置StackPane的大小以适应整个窗口（如果需要的话）
        //root.setPrefSize(); // 这可能会裁剪图像，除非窗口大小与图像匹配

        // 创建场景并将root设置为场景的根
        Scene scene = new Scene(root);

        // 设置窗口标题和场景
        primaryStage.setTitle("Image Clicker");
        primaryStage.setScene(scene);

        // 显示窗口
        primaryStage.show();
        // 定时更新图片
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    File file = new File(fileUrl);
                    long l = file.lastModified();
                    Date date1 = new Date(l);
                    String da_up = date1_up.toString();
                    String da = date1.toString();
                    if (!da_up.equals(da))
                    {
                        date1_up=date1;
                        updateImage();
                        Date date=new Date();
                        updateTime = format.format(date);
                        label.setText(updateTime);
                        label.setTextFill(Color.GREEN);

                    }

                });
            }
        }, 0, 500); // 每500ms更新一次图片
        Timer timer1=new Timer();
        timer1.schedule(new TimerTask(){

            @Override
            public void run() {
                Platform.runLater(() -> {
                    String re = get("http://localhost:5000/getDevStatus", null);
                    if (re.equals("1")) {
                        label_status1.setText("正在运行");
                        label_status1.setBackground(new Background(new BackgroundFill(Color.GREEN, CornerRadii.EMPTY, Insets.EMPTY)));
                    }else{
                        try {
                            Thread.sleep(10000);
                            re = get("http://localhost:5000/getDevStatus", null);
                            if (re.equals("1")) {
                                return;
                            }
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        label_status1.setText("设备停止/或异常");
                        label_status1.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
                    }
                });
            }
        },0,10000); //10更新一次

    }
    private void updateImage() {
        try {
//            URL url = new URL("C:\\Users\\23659\\Desktop\\yolov5-master\\yolov5-master\\output.jpg"); // 替换为你的图片URL
//            InputStream is = url.openStream();
            Image image = new Image(fileUrl);
            imageView.setImage(image);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
        public static void main(String[] args) {
        launch(args);
    }

    //滑动事件
    public void inte_slip(Integer x1,Integer y1,Integer x2,Integer y2){
        try {
            // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String url = "http://127.0.0.1:8080//api/swipe";
            HttpPost httpPost = new HttpPost(url);
            //String postData = "dur=1600&x=10000&y=10000&id=1-13";
            Map<String,Object> map=new HashMap<>();
            Random random=new Random();
            int i = random.nextInt(100);
            map.put("dur",360+i);
            map.put("x1",x1*30.3398);
            map.put("y1",y1*14.1743);
            map.put("x2",x2*30.3398);
            map.put("y2",y2*14.1743);
            String id = textArea_id.getCharacters().toString();
            map.put("id",id);
            JSONObject json=new JSONObject(map);
            //String postData = "{\"dur\":\"1700\",\"x\":\"10000\",\"y\":\"10000\",\"id\":\"1-10\"}";
            String postData = json.toJSONString();
            System.out.println("postData = " + postData);
            // 设置请求体为JSON数据
            StringEntity entity = new StringEntity(postData, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json");
            // 发送POST请求并获取响应

            HttpResponse response = httpClient.execute(httpPost);
            // 读取响应内容并打印
            System.out.println(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));

            // 关闭HttpClient连接
            httpClient.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //数据访问通用
    public String setZhu(String url,Map<String,Object> map){
        try {
            // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            if (map!=null){
                JSONObject json=new JSONObject(map);
                String postData = json.toJSONString();
                System.out.println("postData = " + postData);
                // 设置请求体为JSON数据
                StringEntity entity = new StringEntity(postData, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
            }

            httpPost.setHeader("Content-Type", "application/json");
            // 发送POST请求并获取响应

            HttpResponse response = httpClient.execute(httpPost);
            // 读取响应内容并打印

            // 关闭HttpClient连接

            String resu = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            httpClient.close();

            System.out.println("resu = " + resu);
            return resu;

        }catch (Exception e){
            e.printStackTrace();
            return "erro";
        }

    }
    //get请求
    public String get(String url,Map<String,Object> map){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet=new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String s = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            httpClient.close();
            return s;

        } catch (IOException e) {
            try {
                httpClient.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }

    public void click(double x,double y){
        // 生成动作信息
        try {
            // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String url = "http://127.0.0.1:8080//api/click";
            HttpPost httpPost = new HttpPost(url);
            //String postData = "dur=1600&x=10000&y=10000&id=1-13";
            Map<String,Object> map=new HashMap<>();
            Random random=new Random();
            int i = random.nextInt(100);
            map.put("dur",160+i);
            map.put("x",x*30.3398);
            map.put("y",y*14.1743);
            String id = textArea_id.getCharacters().toString();
            map.put("id",id);
            JSONObject json=new JSONObject(map);
            //String postData = "{\"dur\":\"1700\",\"x\":\"10000\",\"y\":\"10000\",\"id\":\"1-10\"}";
            String postData = json.toJSONString();
            System.out.println("postData = " + postData);
            // 设置请求体为JSON数据
            StringEntity entity = new StringEntity(postData, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json");
            // 发送POST请求并获取响应

            HttpResponse response = httpClient.execute(httpPost);
            // 读取响应内容并打印
            System.out.println(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));

            // 关闭HttpClient连接
            httpClient.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        // 处理或返回动作信息
    }
}